<template>
  <div class="users-container">
    <h2>用户管理</h2>
    
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.userName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="searchForm.userRealName" placeholder="请输入真实姓名" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="用户状态">
          <el-select 
            v-model="searchForm.type" 
            placeholder="请选择用户状态" 
            clearable
            style="width: 120px"
          >
            <el-option label="全部" :value="2" />
            <el-option label="正常用户" :value="0" />
            <el-option label="已注销" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户列表 -->
    <el-table :data="userList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="userName" label="用户名" />
      <el-table-column prop="userRealName" label="真实姓名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="createdAt" label="注册时间" :formatter="formatDateTime" />
      <el-table-column prop="admin" label="是否管理员">
        <template #default="scope">
          <el-tag :type="scope.row.role === '管理员' ? 'success' : 'info'">
            {{ scope.row.role === '管理员' ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="380">
        <template #default="scope">
          <template v-if="scope.row.userName !== '该用户已注销'">
            <el-button 
              :type="scope.row.role === '管理员' ? 'danger' : 'primary'"
              size="small" 
              @click="handleSetRole(scope.row, 'admin')"
            >
              {{ scope.row.role === '管理员' ? '取消管理员' : '任命为管理员' }}
            </el-button>
            <el-button 
              type="success"
              size="small" 
              @click="handlePresidentManage(scope.row)"
            >
              社长管理
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleResetPassword(scope.row)"
            >
              重置密码
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(scope.row)"
            >
              注销
            </el-button>
          </template>
          <template v-else>
            <el-tag type="info">已注销</el-tag>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 任命社长对话框 -->
    <el-dialog
      :title="`社长管理 - ${presidentForm.user?.userRealName}`"
      v-model="presidentDialogVisible"
      width="600px"
    >
      <div class="clubs-container" v-loading="loading">
        <el-card 
          v-for="(club, index) in presidentClubs" 
          :key="club.id"
          :class="['club-card', `club-color-${index % 5}`]"
        >
          <div class="club-content">
            <span class="club-name">{{ club.name }}</span>
            <el-button 
              v-if="club.role === '社长'"
              type="danger" 
              size="small" 
              @click="handleCancelPresident(club)"
            >
              取消社长
            </el-button>
          </div>
        </el-card>
        <el-empty v-if="!presidentClubs.length" description="暂无加入的社团" />
      </div>
      <template #footer>
        <el-button @click="presidentDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleAddPresident" :loading="loading">
          添加社团
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加社团对话框 -->
    <el-dialog
      title="添加社团"
      v-model="addClubDialogVisible"
      width="500px"
    >
      <el-form
        ref="presidentFormRef"
        :model="presidentForm"
        :rules="presidentRules"
        label-width="100px"
      >
        <el-form-item label="选择社团" prop="clubId">
          <el-select 
            v-model="presidentForm.clubId" 
            placeholder="请选择社团"
            :disabled="loading"
          >
            <el-option
              v-for="club in availableClubs"
              :key="club.id"
              :label="club.name"
              :value="club.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addClubDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSetPresidentSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'

// 在axios请求拦截器中添加token
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.token = `${token}`;
  }
  return config;
}, error => {
  return Promise.reject(error);
});

// 添加响应拦截器处理错误信息
axios.interceptors.response.use(
  response => {
    // 处理成功响应中的消息提示
    if (response.data.status === 'success' && response.data.message) {
      ElMessage.success(response.data.message);
    }
    return response;
  },
  error => {
    // 获取后端返回的错误信息
    if (error.code === 'ERR_CANCELED') {
      return Promise.reject(error);
    }
    const errorMessage = error.response?.data?.message || error.message || '操作失败';
    ElMessage.error(errorMessage);
    return Promise.reject(error);
  }
);

// 列表数据
const userList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchForm = reactive({
  userName: '',
  userRealName: '',
  email: '',
  type: 2  // 默认查询所有用户
})

// 社团列表
const clubList = ref([])

// 任命社长表单
const presidentDialogVisible = ref(false)
const presidentFormRef = ref(null)
const presidentForm = reactive({
  user: null,
  clubId: ''
})

const presidentRules = {
  clubId: [
    { required: true, message: '请选择社团', trigger: 'change' }
  ]
}

// 加载用户列表
const loadUsers = async () => {
  loading.value = true
  try {
    const res = await axios.get('/user/loadDataList', {
      params: {
        pageNo: currentPage.value,
        pageSize: pageSize.value,
        ...searchForm
      }
    })
    if (res.data.status === 'success') {
      userList.value = res.data.data.list
      total.value = res.data.data.totalCount
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadUsers()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    if (key === 'type') {
      searchForm[key] = 2  // 重置时将用户状态设为默认值(全部)
    } else {
      searchForm[key] = ''
    }
  })
  currentPage.value = 1
  loadUsers()
}

// 加载社团列表
const loadClubs = async () => {
  try {
    const res = await axios.get('/club/loadDataList')
    if (res.data.status === 'success') {
      clubList.value = res.data.data.list
    }
  } catch (error) {
    console.error('获取社团列表失败:', error)
  }
}

// 任命角色
const handleSetRole = async (row, role) => {
  if (role === 'admin') {
    const isAdmin = row.role === '管理员'
    try {
      await ElMessageBox.confirm(
        isAdmin ? '确定要取消该用户的管理员身份吗？' : '确定要将该用户任命为管理员吗？',
        '提示',
        { type: 'warning' }
      )
      const res = await axios.post('/user/setAdmin', {
        userId: row.userId,
        userRealName: row.userRealName,
        userName: row.userName,
        email: row.email,
        setAdmin: !isAdmin  // true表示设置为管理员，false表示取消管理员
      })
      if (res.data.status === 'success') {
        loadUsers()
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('管理员操作失败:', error)
      }
    }
  } else if (role === 'president') {
    const isPresident = row.role === '社长'
    if (isPresident) {
      try {
        await ElMessageBox.confirm('确定要取消该用户的社长身份吗？', '提示', {
          type: 'warning'
        })
        const res = await axios.post('/user/setPresident', {
          userId: row.userId,
          userRealName: row.userRealName,
          userName: row.userName,
          email: row.email,
          setPresident: false  // false表示取消社长
        })
        if (res.data.status === 'success') {
          loadUsers()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消社长失败:', error)
        }
      }
    } else {
      presidentForm.user = row
      presidentDialogVisible.value = true
    }
  }
}

// 提交任命社长
const handleSetPresidentSubmit = async () => {
  if (!presidentFormRef.value) return
  
  await presidentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await axios.post('/user/setPresident', {
          userId: presidentForm.user.userId,
          userRealName: presidentForm.user.userRealName,
          userName: presidentForm.user.userName,
          email: presidentForm.user.email,
          clubId: presidentForm.clubId,
          setPresident: true  // true表示设置为社长
        })
        if (res.data.status === 'success') {
          addClubDialogVisible.value = false
          // 重新获取该用户的社团列表
          const clubRes = await axios.get(`/club/getMyClub`, {
            params: { userId: presidentForm.user.userId }
          })
          if (clubRes.data.status === 'success') {
            presidentClubs.value = clubRes.data.data
          }
        }
      } catch (error) {
        console.error('任命社长失败:', error)
      }
    }
  })
}

// 重置密码
const handleResetPassword = async (row) => {
  try {
    await ElMessageBox.confirm('确定要重置该用户的密码吗？', '提示', {
      type: 'warning'
    })
    const res = await axios.post('/user/resetPassword', {
      userId: row.userId,
      userRealName: row.userRealName,
      userName: row.userName,
      email: row.email
    })
    if (res.data.status === 'success') {
      ElMessage.success(res.data.data)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
    }
  }
}

// 注销用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要注销该用户吗？', '提示', {
      type: 'warning'
    })
    const res = await axios.post('/user/deleteUser', {
      userId: row.userId,
      userRealName: row.userRealName,
      userName: row.userName,
      email: row.email
    })
    if (res.data.status === 'success') {
      ElMessage.success('注销成功')
      loadUsers()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('注销用户失败:', error)
    }
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadUsers()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadUsers()
}

// 格式化时间
const formatDateTime = (row, column) => {
  return row[column.property] ? dayjs(row[column.property]).format('YYYY-MM-DD HH:mm:ss') : ''
}

// 当前用户担任社长的社团列表
const presidentClubs = ref([])
const addClubDialogVisible = ref(false)

// 可选的社团列表（排除已有社长的社团）
const availableClubs = computed(() => {
  return clubList.value.filter(club => {
    return !presidentClubs.value.some(pc => pc.id === club.id && pc.role === '社长')
  })
})

// 处理社长管理
const handlePresidentManage = async (row) => {
  presidentForm.user = row
  presidentDialogVisible.value = true
  loading.value = true
  try {
    // 获取该用户的社团列表
    const res = await axios.get(`/club/getMyClub`, {
      params: { userId: row.userId }
    })
    if (res.data.status === 'success') {
      presidentClubs.value = res.data.data
    }
  } catch (error) {
    console.error('获取社团信息失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理添加社团
const handleAddPresident = () => {
  presidentForm.clubId = ''
  addClubDialogVisible.value = true
}

// 取消社长身份
const handleCancelPresident = async (club) => {
  try {
    await ElMessageBox.confirm(`确定要取消 ${presidentForm.user.userRealName} 在 ${club.name} 的社长身份吗？`, '提示', {
      type: 'warning'
    })
    const res = await axios.post('/user/setPresident', {
      userId: presidentForm.user.userId,
      userRealName: presidentForm.user.userRealName,
      userName: presidentForm.user.userName,
      email: presidentForm.user.email,
      clubId: club.id,
      setPresident: false
    })
    if (res.data.status === 'success') {
      // 重新获取该用户的社团列表
      const clubRes = await axios.get(`/club/getMyClub`, {
        params: { userId: presidentForm.user.userId }
      })
      if (clubRes.data.status === 'success') {
        presidentClubs.value = clubRes.data.data
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消社长失败:', error)
    }
  }
}

onMounted(() => {
  loadUsers()
  loadClubs()
})
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  z-index: 1;
  position: relative;
}

.current-president-section,
.add-president-section {
  margin-bottom: 20px;
}

.president-clubs {
  margin-top: 10px;
}

.president-club-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}

h4 {
  margin: 0 0 10px;
  color: #606266;
}

.clubs-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  padding: 16px;
}

.club-card {
  transition: all 0.3s;
}

.club-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.club-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.club-name {
  font-size: 16px;
  font-weight: 500;
}

/* 不同的社团底色 */
.club-color-0 {
  border-bottom: 3px solid #409EFF;
}

.club-color-1 {
  border-bottom: 3px solid #67C23A;
}

.club-color-2 {
  border-bottom: 3px solid #E6A23C;
}

.club-color-3 {
  border-bottom: 3px solid #F56C6C;
}

.club-color-4 {
  border-bottom: 3px solid #909399;
}

:deep(.el-pagination) {
  margin: 0;
  padding: 0;
}
</style> 